import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from "@angular/forms";
import {ActivatedRoute} from "@angular/router";
import {UserTableComponent} from "../../shared/component/user-table/user-table.component";
import {Condition} from "../../shared/model/condition";
import {CamSearchService} from "../../shared/service/cam-search.service";
import {SingleOpenWinService} from "../../shared/service/single-open-win.service";
import {User} from "../../shared/model/user";
import {CamRecordTableComponent} from "../cam-record-table/cam-record-table.component";
import {Application} from "../../shared/model/application";
import {CamRecordService} from "../../shared/service/cam-record.service";
import {CamManageService} from "../../shared/service/cam-manage.service";
declare var $:any;

@Component({
  selector: 'app-cam-record-home',
  templateUrl: './cam-record-home.component.html',
  styleUrls: ['./cam-record-home.component.css']
})
export class CamRecordHomeComponent implements OnInit {
  @ViewChild
  (CamRecordTableComponent) table :CamRecordTableComponent;
//高级查询参数(modal)
  isVisible = false;
  highForm:FormGroup;
  disabled:boolean = true;
  userId:string = this.routerInfo.snapshot.queryParams["userId"];     //当前登陆者ID
  status:number = -1;       //用车申请状态  0：审批中（流程进行中）；1：已审批（流程正常结案）；2：已撤销（申请人操作）；3：已终止（审批人操作） 4：取消（结案之后，派车之前，申请人可以取消出车申请）'
  applicant :string = ""; //申请人员（普通员工默认为登录者自己，车辆管理员可以选择）;
  condition:Condition = new Condition();
  userSelected:User; //选择的申请人
  statuses:any = [{
    "id":0,
    "name":"审批中"
  },{
    "id":1,
    "name":"已审批"
  },{
    "id":2,
    "name":"已撤销"
  },{
    "id":3,
    "name":"已终止"
  },{
    "id":4,
    "name":"已取消"
  }];

  starttime:string = "";  //开始时间
  endtime:string = "";  //结束时间
  selectedData = [];
  applicationList:Application[]=[];
  vehicleOid:string="";
  allCheckbox:boolean = false;
  _dataSet = [];
  _total = 1;
  _current = 1;
  _pageSize = 10;
  _loading = true;
  //选择框
  _allChecked = false;
  _displayData: Array<any> = [];
  _checkedNumber = 0;
  _checkInfo= [];
  checkAllInfo = [];

  @ViewChild
  (UserTableComponent) userTable :UserTableComponent;
  constructor(public fb:FormBuilder,
              private routerInfo:ActivatedRoute,
              private camSearchService:CamSearchService,
              private singleOpenWinService:SingleOpenWinService,
              private camRecordService:CamRecordService,
              private routeInfo:ActivatedRoute,
              private camManageService:CamManageService) { }

  ngOnInit() {
   // this.checkUser();//验证登录者
    this.createForm();
    this.singleOpenWinService.valueChange.subscribe((info:string)=>{
      this.userSelected = this.userTable.selected;
      if(info == "applicant"){  //申请人开窗
        $("#applicantName").val(this.userSelected.name)
        $("#applicant").val(this.userSelected.id);
      }
      this.userIsVisible = false;
    });

    this.camManageService.oidEvent.subscribe((oid)=>{
      if(oid != ""&& oid != null){
        this.vehicleOid=oid;
        this.refreshData();
      }else{
        this._dataSet = [];
        this._displayData = [];
        this.applicationList = [];
      }
    });
  }

  createForm(){
    this.highForm = this.fb.group({
      status:-1,
      applicantName:'',
      applicant:''
    });
  }

  refreshDataTable(){
    this.table.ngOnInit();
  }

/*  //判断当前登录者是否是车辆管理员
  checkUser(){
    this.camSearchService.checkUser(this.userId).then(
      res =>{
        if(res.code === 1){
          this.disabled = false;//表示当前登录者是车辆管理员
        }else{
          this.disabled = true;
        }
        this.getCondition();
      }
    )
  }*/

  //取消操作
  handleCancel = (e) => {
    this.isVisible = false;
  }

//高级查询
  btn_detailedSearch(){
    this.showModal();
    /*if(this.disabled === true){
      $('#applicant').val(this.userId);
    }*/
  }

  //人员查询
  openwin(){
    this.userTable.source = "applicant";
    this.userShowModal();
  }
  //清空申请人栏位
  clear(){
    $("#applicantName").val('');
    $("#applicant").val('');
  }

  showModal = () => {
    this.isVisible = true;
    $("#status").val(this.status);
  }

  /**
   *  单选人员开窗
   */
  userIsVisible = false;
  userShowModal = () => {
    this.userIsVisible = true;
  }
  userHandleCancel = (e) => {
    this.userIsVisible = false;
  }

  //高级查询确定按钮
  detailedSearch(){
    this.status= $('#status').val();
    this.applicant= $('#applicant').val();
    this.refreshData();
    this.isVisible = false;

  }

  refreshData(reset = false){
    if (reset) {
      this._current = 1;
    }
    this._loading = true;
    this.getCamApplyInfoByVehicle();
  }

  _displayDataChange($event) {
    this._displayData = $event;
  };

  _checkAll(value) {
    if (value) {
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status!=0&&this._displayData[i].status!= 1){
          this._displayData[i].checked = true;
        }
      }
    } else {
      this._displayData.forEach(data => data.checked = false);
      for(let i=0;i<this._displayData.length;i++){
        let numb = this.checkAllInfo.indexOf(this._displayData[i].oid);
        if(numb!=-1){
          this.checkAllInfo.splice(numb,1);
        }
      }
    }
    this._refreshStatus("","");
  };

  //当前页checkbox选中判断
  _refreshStatus(event,oid) {
    //全选判断
    if(this._displayData.length>0){
      let count:number = 0;
      let checkNumb:number = 0;
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status !=0&&this._displayData[i].status != 1){
          count++;
          if(this._displayData[i].checked == true){
            checkNumb++;
          }
        }
      }
      if(checkNumb!=0 && count==checkNumb){
        this._allChecked = true;
      }else{
        this._allChecked = false;
      }
    }
    this._checkedNumber = this._dataSet.filter(value => value.checked).length;
    this._checkInfo = this._dataSet.filter(value => value.checked);  //存放选中行的信息
    //判断是否有checkbox取消事件
    if(event==false){
      let numb = this.checkAllInfo.indexOf(oid);
      if(numb!=-1){
        this.checkAllInfo.splice(numb,1);
      }
    }
  };

  //选择判断
  select(selectedData:any,currentData:any){
    let selectInfo = [];
    if(selectedData){
      for(var i=0;i<currentData.length;i++){
        for(var j=0;j<selectedData.length;j++){
          if(currentData[i].oid == selectedData[j]){
            selectInfo.push(currentData[i]);
          }
        }
      }
      selectInfo.forEach(data => data.checked = true);
    }
  }

  //删除出车记录
  delInfo(){
    //将当前页所选会议信息插入所有选择信息变量checkAllInfo中
    for(var i=0;i<this._checkInfo.length;i++){
      if(this.checkAllInfo.indexOf(this._checkInfo[i].oid) == -1){
        this.checkAllInfo.push(this._checkInfo[i].oid);
      }
    }
    if(this.checkAllInfo.length>0){
      if(confirm("共选择"+this.checkAllInfo.length+"条出车记录，删除后将无法恢复，确定要删除吗？\n")){
        for(let i=0;i<this.checkAllInfo.length;i++){
          this.camRecordService.deleteApplication(this.checkAllInfo[i]);
        }
        alert("删除成功！\n");
        this.checkAllInfo = [];
        this._checkInfo = [];
        this._current = 1;
        this.refreshData();
      }
    }else{
      alert("请至少选择一条出车记录！\n");
    }
  }

  //根据车辆，查询所有用车记录
  getCamApplyInfoByVehicle(){
    let exclude = "";
    if(this.status == -1){
      exclude = "2,3";
    }else if(this.status == 0){
      exclude = "1,2,3,4";
    }else if(this.status == 1){
      exclude = "0,2,3,4";
    }else if(this.status == 2){
      exclude = "0,1,3,4";
    }else if(this.status == 3){
      exclude = "0,1,2,4";
    }else if(this.status == 4){
      exclude = "0,2,3,1";
    }
    if(typeof (this.applicant)==="undefined"){
      this.applicant="";
    }
    this._current = 1;
    if(this.vehicleOid) {
      this.camRecordService.getCamApplyInfoByVehicle(this._current, this._pageSize, this.applicant, this.vehicleOid, exclude).then(res => {
        this.applicationList = res.list;
        this.allCheckbox = false;
        for (let i = 0; i < this.applicationList.length; i++) {
          //判断用车记录状态
          let statusname = "";
          let date = new Date();
          this.applicationList[i].cancel = false;
          switch (this.applicationList[i].status) {
            case 0:
              statusname = "审批中";
              break;
            case 1:
              statusname = "已审批";
              if (date < new Date(this.applicationList[i].starttime)) {
                this.applicationList[i].cancel = true;
              }
              break;
            case 2:
              statusname = "已撤销";
              break;
            case 3:
              statusname = "已终止";
              break;
            case 4:
              statusname = "已取消";
              break;
          }
          this.applicationList[i].statusname = statusname;
          //判断全选框是否显示
          if (this.applicationList[i].status != 0 && this.applicationList[i].status != 1) {
            this.allCheckbox = true;
          }
        }
        this._dataSet = res.list;
        this._loading = false;
        this._total = res.total;
        this._displayData = res.list;
        //查询选中
        for (var i = 0; i < this._checkInfo.length; i++) {
          if (this.checkAllInfo.indexOf(this._checkInfo[i].oid) == -1) {
            this.checkAllInfo.push(this._checkInfo[i].oid);
          }
        }
        //选择判断
        this.select(this.checkAllInfo, this._dataSet);

        //全选判断
        this._refreshStatus("", "");

      })
    }

  }
}
